package com.allwees.bs.c.module.order.context.compute.strategy.shipping;

import com.allwees.bs.c.module.order.context.bo.CouponComputeBo;
import com.allwees.core.common.util.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author mouhn
 * <p>
 * 满减运费
 */
@Service
public class FullReduceShippingStrategy implements ShippingStrategy {

    @Value("${system.params.order.shipping.reachReduce:50}")
    private String reachReduce;

    @Override
    public CouponComputeBo strategy(CouponComputeBo bo) {
        if (MoneyUtil.isLtEqZero(bo.getAmtShipping())) {
            return bo;
        }

        String value = this.reachReduce;
        if (StringUtils.isBlank(value) || !NumberUtils.isCreatable(value)) {
            return bo;
        }

        BigDecimal fullFree = new BigDecimal(value).setScale(2, BigDecimal.ROUND_HALF_UP);

        //不大于设定金额时计算运费
        if (bo.getAmtProduct().compareTo(fullFree) < 0) {
            if (0 == bo.getDiscountRate().intValue()) {
                bo.setDiscountRate(new BigDecimal(1));
            }
            BigDecimal needToPayForFreeShipping = MoneyUtil.div(fullFree,bo.getDiscountRate());
            bo.setDeductMore(MoneyUtil.sub(needToPayForFreeShipping,bo.getAmtProduct()));
            return bo;
        }
        bo.getItems().forEach(item -> {
            item.setAmtShippingDiscountSku(item.getAmtShipping());
            item.setShippingAmtSkuAfterAdd(BigDecimal.ZERO);
            item.setAmtShipping(BigDecimal.ZERO);
            item.computeAmt();
        });

        bo.setAmtShippingDiscount(bo.getAmtShipping());
        bo.setAmtShipping(BigDecimal.ZERO);
        bo.setAmtShippingAfterAdd(BigDecimal.ZERO);
        return bo.computeAmt();
    }
}
